import type { App, Directive, DirectiveBinding } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'

function checkPermission(el: HTMLElement, binding: DirectiveBinding): boolean {
  const { value, modifiers } = binding
  const authStore = useAuthStore()
  const userPermissions = authStore.permissions || []

  const codes = Array.isArray(value) ? value : [value]

  // 使用 every 修饰符时，需要满足所有权限
  const hasPermission = modifiers.every
    ? codes.every((code) => userPermissions.includes(code))
    : codes.some((code) => userPermissions.includes(code))

  if (!hasPermission && el.parentNode) {
    el.parentNode.removeChild(el)
  }

  return hasPermission
}

export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  },
}

export function setupPermission(app: App) {
  app.directive('permission', permission)
}
